package com.siyoumi.app.modules.lucky_num.admin;

import com.siyoumi.app.entity.LnumGroup;
import com.siyoumi.app.modules.lucky_num.entity.LuckyNumType;
import com.siyoumi.app.modules.lucky_num.service.SvcLNumGroup;
import com.siyoumi.app.modules.lucky_num.service.SvcLnumNumSet;
import com.siyoumi.app.modules.lucky_num.vo.VaLnumGroup;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.util.IEnum;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.validator.XValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/lucky_num/lucky_num__group__edit")
public class lucky_num__group__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        setPageTitle("号码组-编辑");

        InputData inputData = InputData.fromRequest();
        String type = inputData.input("type");

        Map<String, Object> data = new HashMap<>();
        data.put("lngroup_order", 0);
        data.put("lngroup_type", type);
        if (isAdminEdit()) {
            LnumGroup entity = SvcLNumGroup.getApp().loadEntity(getID());

            HashMap<String, Object> dataAppend = new LinkedHashMap<>();
            dataAppend.put("id", entity.getKey());
            //
            //合并
            data = entity.toMap();
            data.putAll(dataAppend);
        }
        getR().setData("data", data);

        //类型
        setPageInfo("group_type", IEnum.toMap(LuckyNumType.class));

        Boolean setNum = false;
        if (SvcLNumGroup.isLuckyNum((String) data.get("lngroup_type"))) {
            //初始化，号码设置
            SvcLnumNumSet.getBean().editAfter(inputData, getR(), getID());
            setNum = true;
        }
        setPageInfo("set_num", setNum);

        return getR();
    }


    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/save")
    public XReturn save(@Validated() VaLnumGroup vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result);
        //
        if (!isAdminEdit()) {
            vo.setLngroup_acc_id(getAccId());
        } else {
            vo.setLngroup_type(null);
            vo.setLngroup_acc_id(null);
        }

        InputData inputData = InputData.fromRequest();
        return SvcLNumGroup.getBean().edit(inputData, vo);
    }
}